package com.ssm.demo.service.mail.impl;

import com.ssm.demo.service.mail.IMailSenderService;
import com.ssm.demo.service.tbuser.bean.User;
import freemarker.template.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

@Service
public class MailSenderServiceImpl implements IMailSenderService {

    private final static Logger logger = LoggerFactory.getLogger(MailSenderServiceImpl.class);

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private Configuration freemarkerConfiguration;

    //异步执行
    @Async
    //@Scheduled(cron="0/5 * *  * * ? ")定时任务，每五秒发送一次
    public void sendMail(final User user){

        final MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,"utf-8");
                helper.setFrom("fxq15712058302@sina.com");
                helper.setTo("15712058302@163.com");
                helper.setSubject("邮件发送测试");
                //使用邮件模板
                Map<String, Object> map = new HashMap<>();
                map.put("user", user);
                String content = geFreeMarkerTemplateContent(map);
                helper.setText(content, true);
                helper.addAttachment("fxq.png", new ClassPathResource("pic/fxq.png"));

            }
        };

        try {
            //开启线程发送
            taskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    javaMailSender.send(preparator);
                    System.out.println("发送成功");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("邮件发送失败", e.getMessage());
        }

    }

    /**
     * 准备邮件数据
     * @param map
     * @return
     */
    private String geFreeMarkerTemplateContent(Map<String, Object> map){

        StringBuffer content = new StringBuffer();
        try {
            content.append(FreeMarkerTemplateUtils.processTemplateIntoString
                          (freemarkerConfiguration.getTemplate("fm-userDeleted.html"), map));
        return content.toString();

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取模板异常");
        }
        return "";
    }


}
